package com.ywgt.system.controller;

import com.ywgt.response.Result;
import com.ywgt.system.pojo.Menu;
import com.ywgt.system.service.MenuService;
import com.ywgt.system.vo.MenuVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author yiping
 * @since 2021-01-18
 */
@RestController
@Api(value = "菜单模块",tags = "菜单模块")
@RequestMapping("/system/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @ApiOperation(value = "获取菜单树",notes = "菜单树列表")
    @GetMapping("/tree")
    public Result getMenuTree(){
        List<Menu> menuTree = menuService.getMenuTree();
        List<Menu> menuList=new ArrayList<>();
        List<Long> ids=new ArrayList<>();
        for (Menu menu : menuList) {
            if (menu.getOpen()==0){
                ids.add(menu.getId());
            }
        }
        return Result.ok().data("tree",menuTree).data("open",ids);
    }

    @ApiOperation(value = "添加菜单",notes = "添加菜单")
    @PostMapping("/add")
    public Result addMenu(@RequestBody MenuVO menuVO){
        Menu menu=new Menu();
        BeanUtils.copyProperties(menuVO,menu);
        Integer type = menuVO.getType();
        menu.setType(String.valueOf(type));
        menu.setAvailable(menuVO.getOpen());
        if (menuService.save(menu)){
            return Result.ok();
        }
        return Result.error();
    }
    @ApiOperation(value = "删除菜单",notes = "根据id删除菜单")
    @DeleteMapping("/delete/{id}")
    public Result delMenu(@PathVariable("id") Long id){
        if (menuService.removeById(id)){
            return Result.ok();
        }
        return Result.error();
    }
    @ApiOperation(value = "修改菜单",notes = "根据id修改菜单")
    @GetMapping("/edit/{id}")
    public Result updateMenu(@PathVariable("id")Long id){
        Menu menu = menuService.getById(id);
        if (menu!=null){
            return Result.ok().data("data",menu);
        }
        return Result.error();
    }
}

